package olegroshka.src.com.bofa.olegroshka.datasource;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

public class DataSourceComposite<D> implements DataSource<D> {

	private final DataSource<D>[] dataSources; 
	private final Queue<Iterator<D>> iterators;
	private Iterator<D> currentIterator; 		
	
	public DataSourceComposite(DataSource<D>... dataSources) {
		if( dataSources == null || dataSources.length == 0 ) {
			throw new IllegalArgumentException("dataSources can't be null or zero length");
		}
		this.dataSources = dataSources;
		this.iterators = new LinkedList<Iterator<D>>();
		for (DataSource<D> dataSource : dataSources) {
			iterators.offer(dataSource.iterator());
		}
		this.currentIterator = this.iterators.poll();
	}

	public Iterator<D> iterator() {
		return new Iterator<D>() {

			public boolean hasNext() {
				boolean hasNext = currentIterator.hasNext();
				while( !hasNext ) {
					currentIterator = iterators.poll();
					hasNext = currentIterator != null ? currentIterator.hasNext() : false;
				}
				return hasNext;
			}

			public D next() {
				return currentIterator != null ? currentIterator.next() : null;
			}

			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}

	public void begin() {
		for (DataSource<D> dataSource : dataSources) {
			dataSource.begin();
		}
	}

	public void end() {
		for (DataSource<D> dataSource : dataSources) {
			dataSource.end();
		}
	}

}
